package ar.com.pragmatia.lanacion;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import ar.com.pragmatia.lanacion.app.App;
import ar.com.pragmatia.lanacion.data.AppData;
import ar.com.pragmatia.lanacion.data.Client;
import ar.com.pragmatia.lanacion.data.Visit;

public class MainVisitActivity extends LaNacionActivity {

	private EditText txtCode;
	private EditText txtName;
	private TableLayout tblClients;
	private Dialog dialog;
	private Context appContext;
	private Date date;
	private static final int DATE_DIALOG_ID = 0;

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			date.setYear(year - 1900);
			date.setMonth(monthOfYear);
			date.setDate(dayOfMonth);
			updateTime();
		}
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.visits_main);

		appContext = this;

		Button btnVisits = (Button) findViewById(R.id.btnVisits);
		if (btnVisits != null) {
			btnVisits.setPressed(true);
		}

		txtCode = (EditText) findViewById(R.id.txtCode);
		txtName = (EditText) findViewById(R.id.txtName);
		tblClients = (TableLayout) findViewById(R.id.tblClients);

		txtCode.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			public void afterTextChanged(Editable s) {
				String text = getFilters();
				Visit cl = new Visit();
				Vector<AppData> v = cl.query(text);
				updateTable(tblClients, v);
			}
		});

		updateTime();
		txtCode.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					// txtCode.clearFocus();
					showDialog(DATE_DIALOG_ID);
				}
			}
		});

		txtName.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			public void afterTextChanged(Editable s) {
				String text = getFilters();
				Visit cl = new Visit();
				Vector<AppData> v = cl.query(text);
				updateTable(tblClients, v);
			}
		});

		Visit visit = new Visit();
		Vector<AppData> visits = visit.find();
		updateTable(tblClients, visits);

		OnClickListener addClient = new OnClickListener() {

			public void onClick(View v) {
				Intent newVisitActivity = new Intent().setClass(
						getApplicationContext(), NewVisitActivity.class);
				startActivity(newVisitActivity);

			}
		};

		Button btnAddClient = (Button) findViewById(R.id.btnAddClient);
		btnAddClient.setOnClickListener(addClient);

		// OnClickListener addVisit = new OnClickListener() {
		//
		// public void onClick(View v) {
		// Intent newVisitActivity = new Intent(getParent(),
		// NewVisitActivity.class);
		// TabGroupActivity parentActivity = (TabGroupActivity) getParent();
		// parentActivity.startChildActivity("newVisitActivity",
		// newVisitActivity);
		//
		// }
		// };
		//
		// Button btnAddVisit = (Button) findViewById(R.id.btnAddVisit);
		// btnAddVisit.setOnClickListener(addVisit);

	}

	private String getFilters() {
		String filter = "SELECT visits.id, visits.seller_id, "
				+ "visits.client_id, visits.contact, visits.reason, "
				+ "visits.result, visits.claim, visits.items_delivered, "
				+ "visits.observations, visits.date, visits.next_visit_date, "
				+ "visits.created, visits.modified,	visits.uuid, visits.sent, visits.location FROM visits";
		String code = txtName.getText().toString();
		if (!code.isEmpty()) {
			filter += " INNER JOIN clients Client ON (visits.client_id = Client.id) WHERE Client.shop_name LIKE '%"
					+ code + "%'";
		}
		String name = txtCode.getText().toString();
		if (!name.isEmpty()) {
			if (!code.isEmpty()) {
				filter += " AND ";
			} else {
				filter += " WHERE ";
			}

			filter += "visits.date LIKE '" + name + "%'";
		}
		return filter;
	}

	private void addTableHeader(TableLayout table) {
		TableRow row = new TableRow(this);

		TextView c = new TextView(this);
		c.setText(getText(R.string.code));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		c = new TextView(this);
		c.setText(getText(R.string.name));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		c = new TextView(this);
		c.setText(getText(R.string.visit_date));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		c = new TextView(this);
		c.setText(getText(R.string.visit_reason));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		c = new TextView(this);
		c.setText(getText(R.string.visit_result));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		row.setBackgroundColor(0xEEEEEEEE);

		table.addView(row, new TableLayout.LayoutParams());
	}

	private void updateTable(TableLayout table, Vector<AppData> clients) {
		table.removeAllViews();
		addTableHeader(table);
		appendRows(table, clients);
	}

	private void appendRows(TableLayout table, Vector<AppData> visits) {
		int rowSize = visits.size();
		for (int i = 0; i < rowSize; i++) {
			TableRow row = new TableRow(this);

			Visit visit = ((Visit) visits.get(i));

			Client client = visit.getClient();

			TextView c = new TextView(this);
			c.setText(client.getClientCode());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			c = new TextView(this);
			c.setText(client.getShopName());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			c = new TextView(this);
			c.setText(visit.getVisitDate());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			c = new TextView(this);
			c.setText(visit.getReason());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			c = new TextView(this);
			c.setText(visit.getResult());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			row.setTag(visit.getId());

			row.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// v.getTag();

					dialog = new Dialog(appContext);
					dialog.setContentView(R.layout.visits_view);

					Visit clt = new Visit();
					Visit visit = (Visit) clt.find("WHERE id = " + v.getTag())
							.get(0);

					App.log("Visit", "toString", visit.toString());

					Client client = visit.getClient();

					dialog.setTitle("");

					if (visit != null) {
						dialog.setTitle(client.getShopName());

						TextView txtShopName = (TextView) dialog
								.findViewById(R.id.txtShopName);
						txtShopName.setText(client.getShopName());

						TextView txtContact = (TextView) dialog
								.findViewById(R.id.txtContact);
						txtContact.setText(visit.getContact());

						TextView txtDateOfVisit = (TextView) dialog
								.findViewById(R.id.txtDateOfVisit);
						txtDateOfVisit.setText(visit.getVisitDate());

						TextView txtVisitReason = (TextView) dialog
								.findViewById(R.id.txtVisitReason);
						txtVisitReason.setText(visit.getReason());

						TextView txtVisitResult = (TextView) dialog
								.findViewById(R.id.txtVisitResult);
						txtVisitResult.setText(visit.getResult());

						TextView txtVisitClaim = (TextView) dialog
								.findViewById(R.id.txtVisitClaim);
						txtVisitClaim.setText(visit.getClaim());

						TextView txtVisitItemsDelivered = (TextView) dialog
								.findViewById(R.id.txtVisitItemsDelivered);
						txtVisitItemsDelivered.setText(visit
								.getItemsDelivered());

						TextView txtObservations = (TextView) dialog
								.findViewById(R.id.txtObservations);
						txtObservations.setText(visit.getObservation());

						TextView txtNextVisitDate = (TextView) dialog
								.findViewById(R.id.txtNextVisitDate);
						txtNextVisitDate.setText(visit.getNextVisitDate());

					}

					// Button cancel = (Button) dialog
					// .findViewById(R.id.btnCancel);
					// cancel.setOnClickListener(new OnClickListener() {
					//
					// @Override
					// public void onClick(View v) {
					// dialog.dismiss();
					//
					// }
					// });
					dialog.show();

				}
			});

			table.addView(row, new TableLayout.LayoutParams());
		}
	}

	protected void updateTime() {
		if (date == null) {
			date = new Date();
		}
		// SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		txtCode.setText(sdf.format(date));
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener,
					date.getYear() + 1900, date.getMonth(), date.getDate());
		}
		return null;
	}
}
